package com.mischa.atc;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;

import sun.misc.Queue;

/**
 * Represents a flight, i.e. an aircraft with a call sign and a set of
 * instructions.
 * 
 * @author Mischa Spelt
 * 
 */
public class Flight {
	private static final String[] airlines = { "KLM", "EZY", "AFR" };

	private Aircraft _aircraft;
	private String _callsign;
	private List<Clearance> _clearances;

	public Flight(Aircraft aircraft) {
		_aircraft = aircraft;
		_callsign = generateCallsign();
		_clearances = new ArrayList<Clearance>();

		_aircraft.setAltitude(5000);
	}

	public void update(float seconds) {
		while (_clearances.size() > 0) {
			_clearances.get(0).execute(this);
			if (_clearances.get(0).isComplete()) {
				_clearances.remove(0);
			}
		}

		_aircraft.stepTime(seconds);
	}

	public Heading getHeading() {
		return _aircraft.getHeading();
	}

	public void turn(float targetHeading) {
		_aircraft.turn(targetHeading);
	}

	public void turn(float targetHeading, int turningDirection) {
		_aircraft.turn(targetHeading, turningDirection);
	}
	

	public Heading getClearedHeading() {
		return _aircraft.getClearedHeading();
	}

	public Coordinate getPosition() {
		return _aircraft.getPosition();
	}

	public String getCallsign() {
		return _callsign;
	}

	public int getAltitude() {
		return _aircraft.getAltitude();
	}

	public int getClearedAltitude() {		
		return _aircraft.getClearedAltitude();
	}
	
	public void maintainAltitude(int clearedAltitude) {
		_aircraft.maintainAltitude(clearedAltitude);
	}

	public int getSpeed() {
		return _aircraft.getSpeed();
	}

	private static String generateCallsign() {
		return airlines[Utilities.randomNumberBetween(0, airlines.length - 1)]
				+ Utilities.randomNumberBetween(100, 9999);
	}

	@Override
	public String toString() {
		return _callsign;
	}

	public void clear(Collection<Clearance> clearances, boolean replaceExisting) {
		if (replaceExisting) {
			_clearances.clear();
		}
		// Add all clearances at the top of the list,
		// in the given order
		_clearances.addAll(0, clearances);
	}

	public void clear(Clearance clearance, boolean replaceExisting) {
		List<Clearance> singletonList = new ArrayList<Clearance>(1);
		singletonList.add(clearance);
		clear(singletonList, replaceExisting);
	}

	public void setSpeed(int i) {
		_aircraft.setSpeed(i);
	}


}
